<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Trieda určená na importovanie/exportovanie eventov používateľov do/z databázy.
 * 
 * @author Michal Foltin
 */
class ImEx_model extends CI_Model {

    function __construct() {
        parent::__construct();
    }

    /**
     * Metóda slúži na import eventov do databázy. Ak event v databáze ešte nie je, tak ho pridá do databázy a pridá ho používateľovi.
     * Ak event v databáze už je ale nepatrí používateľovi, priradí ho používateľovi.
     * 
     * @param array $data - údaje o importovaných eventoch; asociatívne pole 
     * array (
     *         'user' => int,
     *         'events' => array ('event_type', 'description', 'day', 'start_time', 'end_time', 'room')
     * )
     * @return boolean - true ak sa import podaril, false ak nie
     */
    function importEvents($data) {
        if (!isset($data) || !isset($data['user']) || !isset($data['events'])) {
            return false;
        }
        $userID = $data['user'];
        $events = $data['events'];

        $this->db->trans_begin();

        foreach ($events as $event) {
            if (!isset($event['event_type']) || !isset($event['day']) || !isset($event['start_time'])
                    || !isset($event['end_time']) || !isset($event['room']) || !isset($event['description'])) {
                $this->db->trans_rollback();
                return false;
            }

            $getEventSql = "SELECT e.id
                FROM event e
                INNER JOIN event_type et ON et.id = e.event_type
                INNER JOIN room r ON r.id = e.room_id
                WHERE et.event_type = '" . $event['event_type'] . "' AND e.event_day = '" . $event['day']
                    . "' AND e.start_time = " . $event['start_time'] . " AND e.end_time = " . $event['end_time']
                    . " AND r.room_name = '" . $event['room'] . "' AND e.description = '" . $event['description'] . "';";

            $getEvent = $this->db->query($getEventSql);

            if (wasError()) {
                return false;
            }

            if ($getEvent->num_rows() == 0) {
                $getRoom = $this->db->get_where('room', array('room_name' => $event['room']));
                if (wasError()) {
                    return false;
                }
                $roomId = $getRoom->row()->id;
                $getEventType = $this->db->get_where('event_type', array('event_type' => $event['event_type']));
                if (wasError()) {
                    return false;
                }
                $eventTypeId = $getEventType->row()->id;

                $newEvent = array(
                    'event_type' => $eventTypeId,
                    'description' => $event['description'],
                    'event_day' => $event['day'],
                    'start_time' => $event['start_time'],
                    'end_time' => $event['end_time'],
                    'room_id' => $roomId
                );
                $this->db->insert('event', $newEvent);
                if (wasError()) {
                    return false;
                }
                $getNewEvent = $this->db->query($getEventSql);
                if (wasError()) {
                    return false;
                }
                $newEventId = $getNewEvent->row()->id;

                $userEvent = array(
                    'user_id' => $userID,
                    'event_id' => $newEventId
                );
                $this->db->insert('user_events', $userEvent);
                if (wasError()) {
                    return false;
                }
            } else {
                $getUserEventSql = "SELECT *
                FROM user_events
                WHERE event_id = " . $getEvent->row()->id . " AND user_id = " . $userID . ";";
                $getUserEvent = $this->db->query($getUserEventSql);
                if (wasError()) {
                    return false;
                }
                if ($getUserEvent->num_rows() == 0) {
                    $userEvent = array(
                        'user_id' => $userID,
                        'event_id' => $getEvent->row()->id
                    );
                    $this->db->insert('user_events', $userEvent);
                    if (wasError()) {
                        return false;
                    }
                }
            }
        }

        if (wasError()) {
            $this->db->trans_rollback();
            return false;
        } else {
            $this->db->trans_commit();
            return true;
        }
    }

    /**
     * Metóda načíta z databázy záznamy o eventoch vyhovujúcich podmienke $condition. Podmienky musia platiť všetky naraz (AND).
     * Ak nie je zadaná žiadna podmienka, metóda vráti všetky eventy z databázy.
     * 
     * @param array $condition - podmienka pre export údajov
     * $condition = array (
     *    'start_time' => array(540,680), - minTime, maxTime
     *    'end_time' => array(780,820), - minTime, maxTime
     *    'room' => array('A', 'B', 'F1'),
     *    'teacher' => array(547,125), - user id
     *    'event' => array(18327, 18977), - event ids
     *    'date' => array('2012-01-01', '2012-12-31') - minTime, maxTime, alebo array('1','4') - ked ide o dni
     *    'description' => array(string)
     * );
     * 
     * @return array - všetky eventy vyhovujúce podmienke; asociatívne pole: array (event_type, day, start_time, end_time, room, teachers_list)
     */
    function exportEvents($condition) {
        $data = array();
        $getEventsQuery = "SELECT et.event_type, e.description, e.event_day, e.start_time, e.end_time, r.room_name, GROUP_CONCAT(u.first_name, ' ', u.surname SEPARATOR ', ') AS teacher
            FROM user_events ue
            INNER JOIN user_info u ON ue.user_id = u.id
            INNER JOIN event e ON e.id = ue.event_id
            INNER JOIN event_type et ON et.id = e.event_type
            INNER JOIN room r ON r.id = e.room_id
            WHERE 1=1 ";

        if (isset($condition['start_time']) && isset($condition['start_time'][0]) && isset($condition['start_time'][1])) {
            $startTimeCondition = $condition['start_time'];
            $getEventsQuery .= " AND e.start_time between " . $startTimeCondition[0] . " AND " . $startTimeCondition[1];
        }

        if (isset($condition['end_time']) && isset($condition['end_time'][0]) && isset($condition['end_time'][1])) {
            $endTimeCondition = $condition['end_time'];
            $getEventsQuery .= " AND e.end_time between " . $endTimeCondition[0] . " AND " . $endTimeCondition[1];
        }

        if (isset($condition['room']) && !empty($condition['room'])) {
            $getEventsQuery .= " AND r.room_name IN (";
            $rooms = array();
            foreach ($condition['room'] as $value) {
                $room = "'" . $value . "'";
                array_push($rooms, $room);
            }
            $getEventsQuery .= implode($rooms, ', ');
            $getEventsQuery .= ")";
        }

        if (isset($condition['teacher']) && !empty($condition['teacher'])) {
            $getEventsQuery .= " AND u.id IN (";
            $getEventsQuery .= implode($condition['teacher'], ', ');
            $getEventsQuery .= ")";
        }

        if (isset($condition['event']) && !empty($condition['event'])) {
            $getEventsQuery .= " AND e.id IN (";
            $getEventsQuery .= implode($condition['event'], ', ');
            $getEventsQuery .= ")";
        }

        if (isset($condition['date']) && isset($condition['date'][0]) && isset($condition['date'][1])) {
            $DateCondition = $condition['date'];
            $getEventsQuery .= " AND ((e.event_day IN ('1','2','3','4','5')) OR (e.event_day between " . $DateCondition[0] . " AND " . $DateCondition[1]."))";
        }

        if (isset($condition['description']) && !empty($condition['description'])) {
            $getEventsQuery .= " AND e.description IN (";
            $getEventsQuery .= implode($condition['description'], ', ');
            $getEventsQuery .= ")";
        }

        $getEventsQuery .= "
            GROUP BY e.id, et.event_type, e.description, e.event_day, e.start_time, e.end_time, r.room_name
            ORDER BY e.event_day, e.start_time, e.end_time, e.id;";
        
        $getEvents = $this->db->query($getEventsQuery);

        if (wasError()) {
            return array();
        }

        foreach ($getEvents->result() as $row) {
            $event = array(
                'event_type' => $row->event_type,
                'description' => $row->description,
                'day' => $row->event_day,
                'start_time' => $row->start_time,
                'end_time' => $row->end_time,
                'room' => $row->room_name,
                'teachers_list' => $row->teacher
            );
            array_push($data, $event);
        }

        return $data;
    }

}

?>
